package com.csj.mvvm.version

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.fragment.app.FragmentActivity
import com.csj.mvvm.R
import com.csj.mvvm.utils.LogUtil


/**
 * @describe 兼容Android 8.0 APP 在线更新，权限申请界面
 */
@RequiresApi(api = Build.VERSION_CODES.O)
class AndroidOPermissionActivity : FragmentActivity() {
    private var mAlertDialog: AlertDialog? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 弹窗
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.REQUEST_INSTALL_PACKAGES),
                INSTALL_PACKAGES_REQUESTCODE
            )
        } else {
            finish()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            INSTALL_PACKAGES_REQUESTCODE -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
            ) {
                if (sListener != null) {
                    sListener?.permissionSuccess()
                    finish()
                }
            } else {
                showDialog()
            }
        }
    }

    private fun showDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle(R.string.app_name)
        builder.setMessage(
            String.format(
                resources.getString(R.string.sys_apply_permission),
                getString(R.string.app_name)
            )
        )
        builder.setPositiveButton(
            R.string.sys_ensure
        ) { _, _ ->
            startInstallPermissionSettingActivity()
            mAlertDialog!!.dismiss()
        }
        builder.setNegativeButton(
            R.string.sys_cancel
        ) { dialogInterface, i ->
            sListener?.permissionFail()
            mAlertDialog!!.dismiss()
            finish()
        }.setCancelable(false)
        mAlertDialog = builder.create()
        mAlertDialog!!.show()
    }

    private fun startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        val intent = Intent(
            Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
            Uri.parse("package:$packageName")
        )
        startActivityForResult(intent, 1)
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtil.e("aCTo onActivityResult requestCode =$requestCode resultCode=$resultCode")
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            // 授权成功
            if (packageManager.canRequestPackageInstalls())
                sListener?.permissionSuccess()
            else
                sListener?.permissionFail()
        } else {
            // 授权失败
            sListener?.permissionFail()
        }
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        sListener = null
    }

    companion object {
        const val INSTALL_PACKAGES_REQUESTCODE = 1
        var sListener: AppDownloadManager.AndroidOInstallPermissionListener? = null
    }
}
